﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC
{
    public static class UsedIds
    {
        private static readonly object _lockObject = new object();

        private static ThreadSafeLookup<long, string> _usedIds = null;

        public static void Add(long id)
        {
            if (_usedIds == null)
            {
                lock (_lockObject)
                {
                    if (_usedIds == null)
                    {
#if NO_SILVERLIGHT
                        if (File.Exists("C:\\UsedIds.dat"))
                        {
                            byte[] bytes = File.ReadAllBytes("C:\\UsedIds.dat");
                            _usedIds = bytes.DeserializeFromCompressedBinary() as ThreadSafeLookup<long, string>;
                        }
                        else
                        {
                            _usedIds = new ThreadSafeLookup<long, string>();
                        }
#else
                        _usedIds = new ThreadSafeLookup<long, string>();
#endif
                    }
                }
            }

            _usedIds.Add(id, string.Empty);
        }

        public static void Save()
        {
#if NO_SILVERLIGHT
            File.WriteAllBytes("C:\\UsedIds.dat", _usedIds.SerializeToCompressedBinary());
#endif
        }

        public static bool Taken(this long id)
        {
            if (_usedIds == null)
            {
                lock (_lockObject)
                {
                    if (_usedIds == null)
                    {
#if NO_SILVERLIGHT
                        if (File.Exists("C:\\UsedIds.dat"))
                        {
                            byte[] bytes = File.ReadAllBytes("C:\\UsedIds.dat");
                            try
                            {
                                _usedIds = bytes.DeserializeFromCompressedBinary() as ThreadSafeLookup<long, string>;
                            }
                            catch { _usedIds = new ThreadSafeLookup<long, string>(); }
                        }
                        else
                        {
                            _usedIds = new ThreadSafeLookup<long, string>();
                        }
#else
                        _usedIds = new ThreadSafeLookup<long, string>();
#endif
                    }
                }
            }

            return _usedIds.ContainsKey(id);
        }
    }
}